<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="id" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="蓝牙驱动虚拟Id" prop="deviceId">
        <el-input v-model="queryParams.deviceId" placeholder="请输入蓝牙驱动虚拟Id" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="蓝牙Mac地址" prop="deviceMac">
        <el-input v-model="queryParams.deviceMac" placeholder="请输入蓝牙Mac地址" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:report:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:report:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:report:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:report:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="蓝牙驱动虚拟Id" align="center" prop="deviceId" />
      <el-table-column label="蓝牙Mac地址" align="center" prop="deviceMac" />
      <el-table-column label="创建日期" align="center" prop="createTime" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:report:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewChart(scope.row)">查看图表</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:report:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改检测报告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="OpenId" prop="openId">
          <el-input v-model="form.openId" placeholder="请输入OpenId" />
        </el-form-item>
        <el-form-item label="报告编号" prop="reportNum">
          <el-input v-model="form.reportNum" placeholder="请输入报告编号" />
        </el-form-item>
        <el-form-item label="蓝牙驱动虚拟Id" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入蓝牙驱动虚拟Id" />
        </el-form-item>
        <el-form-item label="蓝牙Mac地址" prop="deviceMac">
          <el-input v-model="form.deviceMac" placeholder="请输入蓝牙Mac地址" />
        </el-form-item>
        <el-form-item label="原始数据" prop="arrData">
          <el-input v-model="form.arrData" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备用" prop="arrTemp">
          <el-input v-model="form.arrTemp" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="时间戳" prop="arrTimestamp">
          <el-input v-model="form.arrTimestamp" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="16进制原始数据" prop="hexs">
          <el-input v-model="form.hexs" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看图表对话框 -->
    <el-dialog :visible.sync="chartOpen" width="1200px" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false">
      <div class="chart-container">
        <div class="chart-header">
          <div class="header-title">查看电压:【{{ currentReportId }}】</div>
          <div class="header-actions">
            <span class="close-btn" @click="chartOpen = false">×</span>
          </div>
        </div>
        <div id="voltageChart" style="width: 100%; height: 500px;"></div>
        <div class="chart-info">
          <p><strong>数据统计：</strong></p>
          <p>最大值：{{ chartData.maxValue }} 最小值：{{ chartData.minValue }} 平均值：{{ chartData.avgValue }}</p>
          <p>数据点数：{{ chartData.dataCount }} 个</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/system/report"
import * as echarts from 'echarts'

export default {
  name: "Report",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检测报告表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示图表弹出层
      chartOpen: false,
      // 图表数据
      chartData: {
        maxValue: 0,
        minValue: 0,
        avgValue: 0,
        dataCount: 0
      },
      // 当前图表信息
      currentReportId: null,
      currentVoltageData: [],
      // 下载状态控制
      isDownloading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        openId: null,
        reportNum: null,
        deviceId: null,
        deviceMac: null,
        arrData: null,
        arrTemp: null,
        arrTimestamp: null,
        hexs: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询检测报告列表 */
    getList() {
      this.loading = true
      listReport(this.queryParams).then(response => {
        this.reportList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        openId: null,
        reportNum: null,
        deviceId: null,
        deviceMac: null,
        arrData: null,
        arrTemp: null,
        arrTimestamp: null,
        hexs: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加检测报告"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getReport(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改检测报告"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除检测报告编号为"' + ids + '"的数据项？').then(function () {
        return delReport(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/report/export', {
        ...this.queryParams
      }, `report_${new Date().getTime()}.xlsx`)
    },
    /** 查看图表按钮操作 */
    handleViewChart(row) {
      this.parseHexDataAndShowChart(row.hexs, row.id)
    },
    /** 解析hex数据并显示图表 */
    parseHexDataAndShowChart(hexs, reportId) {
      try {
        // 解析hexs数据
        let hexArray = []
        if (typeof hexs === 'string') {
          try {
            hexArray = JSON.parse(hexs)
          } catch (e) {
            console.error('解析hexs JSON失败:', e)
            this.$modal.msgError('数据格式错误，无法显示图表')
            return
          }
        }

        if (!hexArray || hexArray.length === 0) {
          this.$modal.msgError('没有可用的数据')
          return
        }

        console.log('原始hex数据总数:', hexArray.length)
        console.log('原始hex数据前5条:', hexArray.slice(0, 5)) // 显示前5条数据用于调试

        // 解析电压数据
        const voltageData = this.parseVoltageData(hexArray)

        console.log('解析后的电压数据总数:', voltageData.length)
        console.log('解析后的电压数据前5条:', voltageData.slice(0, 5)) // 显示前5条数据用于调试

        if (voltageData.length === 0) {
          this.$modal.msgError('没有有效的电压数据')
          return
        }

        // 计算统计数据
        const values = voltageData.map(item => item.value)
        this.chartData.maxValue = Math.max(...values)
        this.chartData.minValue = Math.min(...values)
        this.chartData.avgValue = (values.reduce((a, b) => a + b, 0) / values.length).toFixed(2)
        this.chartData.dataCount = voltageData.length

        // 保存当前图表数据
        this.currentReportId = reportId
        this.currentVoltageData = voltageData

        console.log('图表统计数据:', this.chartData)

        // 显示图表
        this.chartOpen = true

        // 在下一个tick中初始化图表，确保DOM已经渲染
        this.$nextTick(() => {
          this.initVoltageChart(voltageData, reportId)
        })

      } catch (error) {
        console.error('解析数据失败:', error)
        this.$modal.msgError('解析数据失败')
      }
    },
    /** 解析电压数据 */
    parseVoltageData(hexArray) {
      const voltageData = []

      hexArray.forEach((hex, index) => {
        if (!hex || hex === '01') return

        try {
          let voltage = 0
          let timestamp = null

          console.log(`解析第${index}条数据: ${hex}, 长度: ${hex.length}`)

          // 根据实际数据格式进行解析
          if (hex.length === 16) {
            // 数据格式：0001 + 时间戳 + 数据
            // 例如：'00016892fd46052d'
            // 前4位：序号 (0001)
            // 中间8位：时间戳 (6892fd46)
            // 后4位：电压数据 (052d)

            const hexData = hex.substring(12, 16) // 取后4位作为电压数据
            voltage = this.convertHexToDecimal(hexData)

            // 提取时间戳
            const timeHex = hex.substring(4, 12) // 取中间8位作为时间戳
            const timeValue = this.convertHexToDecimal(timeHex)

            // 检查时间戳是否合理（Unix时间戳范围）
            if (timeValue > 1000000000 && timeValue < 2000000000) {
              // 看起来是Unix时间戳（秒），但为了确保毫秒精度，使用相对时间
              console.log(`检测到秒级时间戳: ${timeValue}，但使用相对时间确保毫秒精度`)
              timestamp = this.generateRelativeTimestamp(hexArray, index)
            } else if (timeValue > 1000000000000 && timeValue < 2000000000000) {
              // 看起来是Unix时间戳（毫秒）
              timestamp = timeValue
            } else {
              // 使用相对时间（0.1s 间隔）
              timestamp = this.generateRelativeTimestamp(hexArray, index)
            }

            console.log(`解析结果 - 电压: ${voltage}, 时间戳: ${timestamp}, 原始时间hex: ${timeHex}, 时间值: ${timeValue}`)
            console.log(`时间戳类型: ${timeValue > 1000000000 && timeValue < 2000000000 ? '秒级时间戳' : timeValue > 1000000000000 && timeValue < 2000000000000 ? '毫秒级时间戳' : '使用相对时间'}`)
          } else if (hex.length === 20) {
            // 双环设备数据格式：0000 + 时间戳 + 数据1 + 数据2
            const hexData1 = hex.substring(12, 16)
            voltage = this.convertHexToDecimal(hexData1)

            const timeHex = hex.substring(4, 12)
            const timeValue = this.convertHexToDecimal(timeHex)

            // 检查时间戳是否合理
            if (timeValue > 1000000000 && timeValue < 2000000000) {
              // 秒级时间戳，使用相对时间确保毫秒精度
              console.log(`双环设备检测到秒级时间戳: ${timeValue}，使用相对时间确保毫秒精度`)
              timestamp = this.generateRelativeTimestamp(hexArray, index)
            } else if (timeValue > 1000000000000 && timeValue < 2000000000000) {
              timestamp = timeValue
            } else {
              // 使用相对时间（0.1s 间隔）
              timestamp = this.generateRelativeTimestamp(hexArray, index)
            }
          } else if (hex.length === 8) {
            // 简单格式：数据 + 电压
            const hexData = hex.substring(0, 4)
            voltage = this.convertHexToDecimal(hexData)

            // 使用相对时间（0.1s 间隔）
            timestamp = this.generateRelativeTimestamp(hexArray, index)
          } else if (hex.length === 24) {
            // 扩展格式：0000 + 时间戳 + 0000 + 数据
            const hexData = hex.substring(20, 24)
            voltage = this.convertHexToDecimal(hexData)

            const timeHex = hex.substring(4, 12)
            const timeValue = this.convertHexToDecimal(timeHex)

            // 检查时间戳是否合理
            if (timeValue > 1000000000 && timeValue < 2000000000) {
              // 秒级时间戳，使用相对时间确保毫秒精度
              console.log(`扩展格式检测到秒级时间戳: ${timeValue}，使用相对时间确保毫秒精度`)
              timestamp = this.generateRelativeTimestamp(hexArray, index)
            } else if (timeValue > 1000000000000 && timeValue < 2000000000000) {
              timestamp = timeValue
            } else {
              // 使用相对时间（0.1s 间隔）
              timestamp = this.generateRelativeTimestamp(hexArray, index)
            }
          }

          // 检查电压值是否有效（大于0且小于合理范围）
          if (voltage > 0 && voltage < 10000) {
            // 如果没有有效的时间戳，使用当前时间减去索引
            if (!timestamp || timestamp <= 0) {
              // 使用相对时间（0.1s 间隔）
              timestamp = this.generateRelativeTimestamp(hexArray, index)
            }

            const date = new Date(timestamp)
            voltageData.push({
              time: this.formatTimeForChart(date),
              value: voltage,
              timestamp: timestamp,
              date: date
            })

            console.log(`添加数据点 - 时间: ${this.formatTimeForChart(date)}, 电压: ${voltage}`)
          } else {
            console.warn(`电压值无效: ${voltage}, 跳过此数据点`)
          }
        } catch (e) {
          console.warn('解析hex数据失败:', hex, e)
        }
      })

      console.log(`总共解析出 ${voltageData.length} 个有效数据点`)

      // 按时间戳排序
      voltageData.sort((a, b) => a.timestamp - b.timestamp)

      return voltageData
    },
    /** 16进制转10进制 */
    convertHexToDecimal(hex) {
      return parseInt(hex, 16)
    },
    /** 生成精确的相对时间戳 */
    generateRelativeTimestamp(hexArray, index) {
      // 使用固定的基准时间，确保毫秒精度
      const baseTime = new Date('2025-09-08 14:15:00.000').getTime()
      const intervalMs = 100 // 100毫秒间隔，确保毫秒精度
      // 从第一个数据点开始，按索引递增时间
      return baseTime + index * intervalMs
    },
    /** 格式化时间为图表显示格式 */
    formatTimeForChart(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      const second = String(date.getSeconds()).padStart(2, '0')
      const ms = String(date.getMilliseconds()).padStart(3, '0')

      // 显示到毫秒，便于 0.1s 采样查看
      return `${year}/${month}/${day} ${hour}:${minute}:${second}.${ms}`
    },
    /** 初始化电压图表 */
    initVoltageChart(voltageData, reportId) {
      this.renderVoltageChart(voltageData, reportId)
    },
    /** 渲染电压图表 */
    renderVoltageChart(voltageData, reportId) {
      const chartDom = document.getElementById('voltageChart')
      if (!chartDom) {
        console.error('找不到图表容器')
        return
      }

      const myChart = echarts.init(chartDom)

      const option = {
        title: {
          text: '原始电压',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 14,
            color: '#666'
          }
        },

        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#409EFF',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: function (params) {
            const data = params[0]
            const value = data.value
            const maxValue = this.chartData.maxValue
            const minValue = this.chartData.minValue
            const avgValue = this.chartData.avgValue

            let status = ''
            if (value === maxValue) {
              status = '<span style="color: #ff4757; font-weight: bold;">(最大值)</span>'
            } else if (value === minValue) {
              status = '<span style="color: #2ed573; font-weight: bold;">(最小值)</span>'
            } else if (Math.abs(value - avgValue) < 5) {
              status = '<span style="color: #ffa502; font-weight: bold;">(接近平均值)</span>'
            }

            return `<div style="padding: 8px;">
               <div style="margin-bottom: 5px;"><strong>时间:</strong> ${data.name}</div>
               <div style="margin-bottom: 3px;"><strong>电压:</strong> ${value} ${status}</div>
               <div style="font-size: 11px; color: #666;">
                 最大值: ${maxValue} | 最小值: ${minValue} | 平均值: ${avgValue}
               </div>
             </div>`
          }.bind(this)
        },
        legend: {
          data: ['电压'],
          top: 60,
          left: 'center',
          itemWidth: 20,
          itemHeight: 10,
          textStyle: {
            fontSize: 12
          }
        },
        toolbox: {
          show: true,
          right: 20,
          top: 20,
          feature: {
            myRefresh: {
              show: true,
              title: '刷新',
              icon: 'path://M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z',
              onclick: function () {
                // 刷新图表
                myChart.setOption(option)
              }
            },
            myTable: {
              show: true,
              title: '表格视图',
              icon: 'path://M912 192H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM912 476H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM912 760H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM160 228a56 56 0 1 0 112 0 56 56 0 1 0-112 0zM160 512a56 56 0 1 0 112 0 56 56 0 1 0-112 0zM160 796a56 56 0 1 0 112 0 56 56 0 1 0-112 0z',
              onclick: function () {
                // 显示表格视图，使用当前最新的数据
                const currentVoltageData = this.currentVoltageData
                const currentReportId = this.currentReportId
                if (currentVoltageData && currentReportId) {
                  this.showTableView(currentVoltageData, currentReportId)
                } else {
                  console.error('当前没有可用的电压数据')
                }
              }.bind(this)
            },

            saveAsImage: {
              title: '下载图片'
            },
            magicType: {
              type: ['bar', 'line'], // 调整顺序，柱状图在前
              title: {
                bar: '柱状图',
                line: '折线图'
              }
            }
          },
          iconStyle: {
            borderColor: '#409EFF'
          }
        },
        xAxis: {
          type: 'category',
          data: voltageData.map(item => item.time),
          axisLabel: {
            rotate: 45,
            fontSize: 10,
            color: '#666',
            interval: Math.max(0, Math.floor(voltageData.length / 7)), // 限制显示数量
            formatter: function (value) {
              // 在数据较多时显示到毫秒
              if (voltageData.length > 50) {
                return value.substring(11, 23) // 显示 时:分:秒.毫秒
              }
              return value
            }
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '电压值',
          nameTextStyle: {
            color: '#666',
            fontSize: 12
          },
          min: Math.floor(this.chartData.minValue * 0.8),
          max: Math.ceil(this.chartData.maxValue * 1.2),
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0',
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#666',
            fontSize: 10
          }
        },
        series: [{
          name: '电压',
          type: 'line', // 默认显示柱状图
          data: voltageData.map(item => item.value),
          smooth: false,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color: '#008004',
            width: 2
          },
          // 柱状图样式配置
          barWidth: '60%',
          barGap: '10%',
          // 柱状图模式下的样式
          barItemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#4cd964'
              }, {
                offset: 1, color: '#008004'
              }]
            },
            borderRadius: [4, 4, 0, 0]
          },
          markLine: {
            silent: true,
            lineStyle: {
              color: '#ffa502',
              type: 'dashed',
              width: 2
            },
            data: [
              {
                yAxis: parseFloat(this.chartData.avgValue),
                label: {
                  formatter: `平均值: ${this.chartData.avgValue}`,
                  color: '#ffa502',
                  fontSize: 12,
                  fontWeight: 'bold',
                  position: 'insideEndTop',
                  offset: [0, 10] // 柱状图模式下调整标签位置
                }
              }
            ]
          },
          markPoint: {
            symbol: 'pin',
            symbolSize: 50, // 柱状图模式下稍微减小标注大小
            symbolOffset: [0, -15], // 柱状图模式下调整标注位置
            data: [
              {
                type: 'max',
                name: '最大值',
                itemStyle: {
                  color: '#ff4757',
                  borderColor: '#fff',
                  borderWidth: 2
                },
                label: {
                  formatter: function (params) {
                    return `最大值\n${params.value}`;
                  },
                  color: '#fff',
                  fontSize: 11,
                  fontWeight: 'bold',
                  backgroundColor: 'rgba(255, 71, 87, 0.8)',
                  padding: [4, 8],
                  borderRadius: 4
                }
              },
              {
                type: 'min',
                name: '最小值',
                itemStyle: {
                  color: '#2ed573',
                  borderColor: '#fff',
                  borderWidth: 2
                },
                label: {
                  formatter: function (params) {
                    return `最小值\n${params.value}`;
                  },
                  color: '#fff',
                  fontSize: 11,
                  fontWeight: 'bold',
                  backgroundColor: 'rgba(46, 213, 115, 0.8)',
                  padding: [4, 8],
                  borderRadius: 4
                }
              }
            ]
          },
          // 柱状图模式下的特殊配置
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          // 默认柱状图样式
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#4cd964'
              }, {
                offset: 1, color: '#008004'
              }]
            },
            borderRadius: [4, 4, 0, 0]
          }
        }],
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        dataZoom: [{
          type: 'inside',
          start: 0,
          end: 100,
          zoomLock: false
        }, {
          type: 'slider',
          start: 0,
          end: 100,
          bottom: 10,
          height: 30,
          borderColor: '#ddd',
          fillerColor: 'rgba(0, 128, 4, 0.1)',
          handleStyle: {
            color: '#008004'
          }
        }]
      }

      myChart.setOption(option)

      // 监听图表类型切换
      myChart.on('magicTypeChanged', function (params) {
        console.log('图表类型切换:', params.currentType)

        if (params.currentType === 'bar') {
          // 柱状图模式下调整配置
          const newOption = {
            series: [{
              markPoint: {
                symbolOffset: [0, -15], // 柱状图模式下调整标注位置
                symbolSize: 50 // 柱状图模式下稍微减小标注大小
              },
              markLine: {
                data: [{
                  yAxis: parseFloat(this.chartData.avgValue),
                  label: {
                    formatter: `平均值: ${this.chartData.avgValue}`,
                    color: '#ffa502',
                    fontSize: 12,
                    fontWeight: 'bold',
                    position: 'insideEndTop',
                    offset: [0, 10] // 柱状图模式下调整标签位置
                  }
                }]
              },
              // 确保柱状图样式正确应用
              barItemStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0, color: '#4cd964'
                  }, {
                    offset: 1, color: '#008004'
                  }]
                },
                borderRadius: [4, 4, 0, 0]
              }
            }]
          }
          myChart.setOption(newOption)
        } else if (params.currentType === 'line') {
          // 折线图模式下恢复配置
          const newOption = {
            series: [{
              markPoint: {
                symbolOffset: [0, -25], // 折线图模式下恢复标注位置
                symbolSize: 60 // 折线图模式下恢复标注大小
              },
              markLine: {
                data: [{
                  yAxis: parseFloat(this.chartData.avgValue),
                  label: {
                    formatter: `平均值: ${this.chartData.avgValue}`,
                    color: '#ffa502',
                    fontSize: 12,
                    fontWeight: 'bold',
                    position: 'insideEndTop',
                    offset: [0, 5] // 折线图模式下恢复标签位置
                  }
                }]
              }
            }]
          }
          myChart.setOption(newOption)
        }
      }.bind(this))

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        myChart.resize()
      })

      // 定义全局函数供工具箱调用
      window.showTableView = (voltageData, reportId) => {
        this.showTableView(voltageData, reportId)
      }
    },
    /** 显示表格视图 */
    showTableView(voltageData, reportId) {
      // 创建表格数据
      const tableData = voltageData.map((item, index) => ({
        index: index + 1,
        time: item.time,
        voltage: item.value
      }))

      // 显示表格弹窗
      this.$confirm('', '表格视图', {
        confirmButtonText: '关闭',
        showCancelButton: false,
        customClass: 'table-dialog',
        dangerouslyUseHTMLString: true,
        message: `
             <div style="max-height: 600px; overflow-y: auto;">
               <div style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
                 <div style="font-size: 14px; color: #666;">
                   共 ${tableData.length} 条数据 | 最大值: ${this.chartData.maxValue} | 最小值: ${this.chartData.minValue} | 平均值: ${this.chartData.avgValue}
                 </div>
                 <button id="downloadTableBtn" style="background: #409eff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                   <i class="el-icon-download" style="margin-right: 4px;"></i>下载数据
                 </button>
               </div>
               <table style="width: 100%; border-collapse: collapse; font-size: 12px; min-height: 400px;">
                                 <thead>
                   <tr style="background-color: #f5f7fa;">
                     <th style="border: 1px solid #ebeef5; padding: 8px; text-align: center; width: 80px;">序号</th>
                     <th style="border: 1px solid #ebeef5; padding: 8px; text-align: center; width: 200px;">时间</th>
                     <th style="border: 1px solid #ebeef5; padding: 8px; text-align: center; width: 100px;">电压值</th>
                   </tr>
                 </thead>
                <tbody>
                  ${tableData.map(item => `
                    <tr>
                      <td style="border: 1px solid #ebeef5; padding: 6px; text-align: center;">${item.index}</td>
                      <td style="border: 1px solid #ebeef5; padding: 6px; text-align: center;">${item.time}</td>
                      <td style="border: 1px solid #ebeef5; padding: 6px; text-align: center;">${item.voltage}</td>
                    </tr>
                  `).join('')}
                </tbody>
              </table>
            </div>
          `
      }).then(() => {
        // 弹窗关闭后的处理
      }).catch(() => {
        // 弹窗关闭后的处理
      })

      // 等待DOM渲染完成后绑定下载按钮事件
      this.$nextTick(() => {
        const downloadBtn = document.getElementById('downloadTableBtn')
        if (downloadBtn) {
          // 使用一次性事件监听器，避免重复绑定
          const handleClick = () => {
            this.downloadTableData(voltageData, reportId)
            // 下载后移除事件监听器
            downloadBtn.removeEventListener('click', handleClick)
          }
          downloadBtn.addEventListener('click', handleClick)
        }
      })
    },

    /** 下载表格数据 */
    downloadTableData(voltageData, reportId) {
      // 防止重复下载
      if (this.isDownloading) {
        this.$message.warning('正在下载中，请稍候...')
        return
      }

      this.isDownloading = true

      try {
        // 创建CSV内容
        const headers = ['序号', '时间', '电压值']
        const csvContent = [
          headers.join(','),
          ...voltageData.map((item, index) => [
            index + 1,
            `"${item.time}"`, // 用引号包围时间，避免CSV解析问题
            item.value
          ].join(','))
        ].join('\n')

        // 添加统计信息
        const statsContent = [
          '',
          '数据统计',
          `最大值,${this.chartData.maxValue}`,
          `最小值,${this.chartData.minValue}`,
          `平均值,${this.chartData.avgValue}`,
          `数据点数,${this.chartData.dataCount}`
        ].join('\n')

        const fullContent = csvContent + statsContent

        // 创建下载链接
        const blob = new Blob(['\ufeff' + fullContent], { type: 'text/csv;charset=utf-8;' })
        const link = document.createElement('a')
        const url = URL.createObjectURL(blob)
        link.setAttribute('href', url)
        link.setAttribute('download', `电压数据_报告${reportId}_${new Date().getTime()}.csv`)
        link.style.visibility = 'hidden'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)

        this.$message.success('数据下载成功')
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      } finally {
        // 延迟重置下载状态，防止快速重复点击
        setTimeout(() => {
          this.isDownloading = false
        }, 1000)
      }
    }
  }
}
</script>

<style scoped>
.chart-container {
  position: relative;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.chart-header {
  position: relative;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-actions .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  font-size: 12px;
  padding: 5px 12px;
  height: 28px;
  line-height: 1;
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: white;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.close-btn:hover {
  color: #ff6b6b;
  transform: translateY(-50%) scale(1.1);
}

.chart-info {
  margin: 0;
  padding: 20px;
  background-color: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.chart-info p {
  margin: 8px 0;
  color: #495057;
  font-size: 14px;
  line-height: 1.5;
}

.chart-info strong {
  color: #212529;
  font-weight: 600;
}




.el-form--inline .el-form-item {
  margin-right: 20px;
}

.el-form--inline .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input {
  width: 200px;
}

.el-button {
  border-radius: 4px;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--default {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #606266;
}

/* 表格弹窗样式 */
.table-dialog .el-message-box {
  width: 95% !important;
  width: 1000px;
  max-width: 2000px !important;
  margin: 0 auto !important;
}

.table-dialog .el-message-box__content {
  padding: 20px;
  max-height: 80vh;
  min-height: 400px;
}

.table-dialog .el-message-box__message {
  padding: 0;
}

.table-dialog table {
  font-family: 'Courier New', monospace;
}

.table-dialog th {
  font-weight: bold;
  background-color: #f5f7fa !important;
}

.table-dialog tr:nth-child(even) {
  background-color: #fafafa;
}

.table-dialog tr:hover {
  background-color: #f0f9ff;
}

.table-dialog td {
  word-break: keep-all;
  white-space: nowrap;
}

.table-dialog th {
  word-break: keep-all;
  white-space: nowrap;
}

/* 下载按钮样式 */
#downloadTableBtn:hover {
  background: #337ecc !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}
</style>
